package servletAction;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;

import util.DomainUtils;
import util.FormArgumentsException;
import domain.dao.interfaces.IDAOUser;
import actionForm.ActionDispatcherValidationForm;
import actionForm.LoginValidationForm;

public class LoginAction  extends Action {
	
	public ActionForward execute(final ActionMapping pMapping,
			ActionForm pForm, final HttpServletRequest pRequest,
			final HttpServletResponse pResponse) {
		final LoginValidationForm lForm = (LoginValidationForm) pForm;
		
		String login = lForm.getLogin();
		HttpSession session = pRequest.getSession(false);

		ApplicationContext context = util.SpringUtils.getApplicationContext();
		try {
			session = pRequest.getSession(true);
			IDAOUser daoUser = (IDAOUser) context.getBean("beanDAOUser");
			session.setAttribute(DomainUtils.CURRENT_USER_STRING, daoUser.getByLogin(login));	
		}
		catch(Exception e) {
			
			if((e instanceof FormArgumentsException) == false) {
				pRequest.setAttribute(DomainUtils.ALERT_ERROR_STRING, "An error occur on the server.");
			}

			DomainUtils.keepParametersContent(pRequest);
		}

		return pMapping.findForward("stay");
	}
}
